package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

//全局异常处理器
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(DuplicateKeyException.class)//声明当前方法要处理的异常类型
    public ResultInfo handlerNameException(DuplicateKeyException e) {
        //1. 记录异常
        e.printStackTrace();

        //2. 返回一个提示
        return ResultInfo.error("当前名字已经占用,请更换");
    }


    @ExceptionHandler(CustomException.class)
    public ResultInfo handlerCustomException(CustomException e) {
        //1. 记录异常
        e.printStackTrace();

        //2. 返回一个提示
        return ResultInfo.error(e.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public ResultInfo handlerCustomException(Exception e) {
        //1. 记录异常
        e.printStackTrace();

        //2. 返回一个提示
        return ResultInfo.error("服务器开小差了,请稍后重试");
    }
}
